<template>
  <div class="page-main">
    <query-page
      ref="queryPageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="renderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      :has-line="false"
      title="暂估信息查看"
      @query-data="getData"
    >
      <template #top-container>
        <a-tabs v-model="activeKey" @change="changeKey">
          <a-tab-pane key="finishedProduct" title="成品" />
          <a-tab-pane key="rawMaterial" title="原材料/锻铸件" />
          <a-tab-pane key="spareParts" title="零部件外包" />
        </a-tabs>
      </template>
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['pms:assessment-info:save']"
            type="primary"
            @click="handleAdd"
            >添加</a-button
          >
          <!-- 批量导入 -->
          <div v-permission="['pms:assessment-info:import']">
            <batch-import
              title="暂估信息导入"
              file-code="pay_estimatedInformation"
              export-type="apiUrl"
              :import-url="`/api/procurement/pay/assessment-info/import`"
              btn-tititle="Excel导入"
              @finish="onFinish"
            />
          </div>
          <!-- <a-button type="outline" @click="openImportExcelModal"
            >Excel导入</a-button
          > -->
          <a-button
            v-permission="['pms:assessment-info:export']"
            @click="handleExport"
            >导出</a-button
          >
        </a-space>
      </template>
      <template #operate="{ record }">
        <a-button
          v-permission="['pms:assessment-info:update']"
          type="text"
          @click="handleEdit(record)"
          >编辑</a-button
        >
        <a-button
          v-permission="['pms:assessment-info:delete']"
          type="text"
          @click="handleDelete(record)"
          >删除</a-button
        >
      </template>
    </query-page>
    <Detail ref="detailRef" />
    <estimatedAdd
      v-if="estimatedAddShow"
      ref="estimatedAddRef"
      v-model="estimatedAddShow"
      :title="moduleTitle"
      @handleCancel="handleCancel"
    />
    <AdvancedFormModal
      ref="importExcelModalRef"
      width="600px"
      title="导入零部件外包"
      :items="importExcelModalConfig"
      @ok="importExcelModalSubmit"
    >
      <template #otherSlot>
        <a-row style="width: 100%" :gutter="[16, 16]">
          <a-col :span="24">
            <a-alert
              >提示：请按模板样式导入Excel
              <a-button type="text" @click="downloadDeptImportTemplate">
                <template #icon> <icon-download /> </template>
                下载模板</a-button
              ></a-alert
            >
          </a-col>
          <a-col :span="24">
            <a-upload
              accept=".xlsx, .xls, .csv"
              :file-list="fileList"
              :limit="1"
              :auto-upload="false"
              :show-cancel-button="false"
              @change="uploadChange"
            >
              <a-button> 选择文件 </a-button>
            </a-upload>
          </a-col>
        </a-row>
      </template>
    </AdvancedFormModal>
  </div>
</template>

<script lang="ts" setup>
  import batchImport from '@/common/components/batch-import/index.vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import { ref, nextTick } from 'vue';
  import { FileItem, Message, Notification } from '@arco-design/web-vue';

  import {
    getQueryPage,
    exportDataToExcel,
    importExcelToData,
    deleteQueryPage,
    downloadTemplate,
  } from '@/api/payment/estimatedInfor';
  import AdvancedFormModal from '@/common/components/cac-components/advanced-form-modal/index.vue';
  import { downFileToExcel } from '@/common/utils/downFile';
  import modalPromise from '@/common/utils/modal-promise';
  import estimatedAdd from './component/estimated-add.vue';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './form-comp/base-form-config';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './table-comp/base-table-config';
  import formRender from './form-comp/form-render';
  import baseRenderKeys from './table-comp/render-table-columns';

  const tableRenderKeys = ref<any[]>([]);
  const activeKey = ref('finishedProduct');
  const tabObj = ref({});
  const mdsItemType = ref([2]);
  const renderKeys = ref<any>([]);
  const detailRef = ref();
  const renderData = ref<any[]>([]);
  const isLoading = ref(true);
  const total = ref(0);
  const selectedKeys = ref([]);
  const estimatedAddShow = ref(false);
  const moduleTitle = ref('');
  const estimatedAddRef = ref();
  const fileList = ref<FileItem[]>([]);
  const importExcelModalRef = ref<any>();
  const init = () => {
    tableRenderKeys.value = baseRenderKeys[activeKey.value];
  };

  tabObj.value = formRender;
  renderKeys.value = tabObj.value.finishedProduct;
  const onFinish = () => {
    console.log('完成');
    // getData();
  };
  const handleExport = async () => {
    const str = mdsItemType.value.join(',');

    const { data, fileName } = await exportDataToExcel({
      mdsItemType: str,
      ...query.value,
    });
    downFileToExcel(fileName, data);
  };
  const mdsItemTypeList = ref({
    finishedProduct: [2],
    rawMaterial: [3, 5],
    spareParts: [4],
  });
  const changeKey = (data: any) => {
    activeKey.value = data;
    renderKeys.value = tabObj.value[data];
    mdsItemType.value = mdsItemTypeList.value[data];
    init();
    getData();
  };
  const query = ref();
  const getData = async (queryInfo: any = {}) => {
    try {
      query.value = queryInfo;
      isLoading.value = true;
      const params = {
        functionType: 0,
        mdsItemType: mdsItemType.value,
        ...queryInfo,
      };
      const { data } = await getQueryPage(params);
      if (data) {
        console.log(data);
        total.value = data.total;
        renderData.value = [...data.list];
      }
      isLoading.value = false;
    } catch (error) {
      Message.warning({
        content: error,
      });
    }
  };
  /**
   * 打开导入Excel对话框
   */
  // const openImportExcelModal = () => {
  //   fileList.value = [];
  //   importExcelModalRef.value.open();
  // };
  // 导入Excel弹窗配置项
  const importExcelModalConfig = [
    {
      span: 24,
      type: 'other',
      labelText: '',
      fieldName: 'otherSlot',
    },
  ];
  /**
   * 导入Excel弹窗提交
   */
  const importExcelModalSubmit = async () => {
    if (fileList.value.length > 0) {
      const formData = new FormData();
      console.log(fileList.value[0].file);
      formData.append('file', fileList.value[0].file as any);
      try {
        isLoading.value = true;
        const res = (await importExcelToData(formData)) as any;
        isLoading.value = false;

        if (res.code === 200) {
          Notification.success({
            content: '导入成功！',
          });
          getData();
        } else {
          Notification.error({
            title: '导入失败！',
            content: res.message,
          });
        }
      } catch (error) {
        isLoading.value = false;
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        Notification.error({
          content: `出现异常！${error}`,
          closable: true,
        });
      }
    } else {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.warning({
        content: '请选择文件！',
        closable: true,
      });
    }
  };
  /**
   * @description 文件上传组件改动触发
   * @param fileList
   * @param file
   */
  const uploadChange = (files: FileItem[], file: FileItem) => {
    file.status = 'uploading';
    fileList.value = [...files];
  };
  const downloadDeptImportTemplate = async () => {
    try {
      const res = await downloadTemplate();
      if (res.type !== 'application/json') {
        const elink = document.createElement('a');
        elink.download = `暂估信息查看下载模板.xlsx`;
        elink.style.display = 'none';
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      } else {
        // 正常情况下文件的下载是不会返回retCode的，如果发现有返回码，说明就是接口出了问题
        Message.error('导出失败');
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Message.error('导出失败');
    }
  };
  const handleAdd = () => {
    moduleTitle.value = '新增';
    estimatedAddShow.value = true;
  };
  const handleEdit = (val: any) => {
    estimatedAddShow.value = true;
    moduleTitle.value = '编辑';
    nextTick(() => {
      estimatedAddRef.value.init(val);
    });
  };
  const handleCancel = () => {
    getData();
  };
  const handleDelete = async (record: any) => {
    try {
      await modalPromise.warning({
        title: '请确认',
        content: '您确定要删除所选的数据？',
        hideCancel: false,
      });
    } catch (error) {
      return;
    }
    await deleteQueryPage(record.id || '');
    Message.success('删除成功');
    getData();
    // Modal.warning({
    //   title: '请确认',
    //   content: '您确定要删除所选的数据？',
    //   hideCancel: false,
    //   onOk: async () => {
    //     await deleteQueryPage(record.id || '');
    //     Message.success('删除成功');
    //     getData();
    //   },
    // });
  };
  init();
</script>

<style lang="less" scoped>
  .arco-btn-outline {
    color: #1e2228 !important;
    border-color: #d9dee7 !important;
  }
</style>
